package com.qixiaobao.common.core.rabbitmq.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @ClassName RabbitMqSendCallback
 * @Author yangxm
 * @Description 消息发送确认机制
 * @Date 2022/12/2 下午2:39
 */
@Component
public class RabbitMqSendCallback implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {

    private static final Logger log = LoggerFactory.getLogger("adminLogger");

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private Jackson2JsonMessageConverter jackson2JsonMessageConverter;


    @PostConstruct
    public void init() {
        //设置开启Mandatory才能触发回调函数，无论消息推送结果怎么样都强制调用回调函数
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setReturnsCallback(this);
        rabbitTemplate.setConfirmCallback(this);
        //设置json转换器
        rabbitTemplate.setMessageConverter(jackson2JsonMessageConverter);
    }

    /**
     * @Description 消息发送到Exchange的回调，无论成功与否
     * @Author yangxm
     * @Date 2022/12/2 下午2:42
     * @Param [correlationData, b, s]
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            log.info("confirm==>发送到broker成功\r\n" +
                            "correlationData={}\r\n" + "ack={}\r\n" + "cause={}",
                    correlationData, ack, cause);
        } else {
            log.error("confirm==>发送到broker失败\r\n" +
                            "correlationData={}\r\n" + "ack={}\r\n" + "cause={}",
                    correlationData, ack, cause);
        }
    }

    /**
     * @Description 消息从Exchange路由到Queue失败的回调
     * @Author yangxm
     * @Date 2022/12/2 下午2:42
     * @Param [returnedMessage]
     */
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        //message（消息体）、replyCode（响应code）、replyText（响应内容）、exchange（交换机）、routingKey（队列）
        log.info("returnedMessage==> \r\n" + "message={}\r\n" + "replyCode={}\r\n" +
                        "replyText={}\r\n" + "exchange={}\r\n" + "routingKey={}",
                returnedMessage.getMessage(), returnedMessage.getReplyCode(), returnedMessage.getReplyText(), returnedMessage.getExchange(), returnedMessage.getRoutingKey());
    }



}
